package hotel.callback.oversea.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author lmf
 * @time 2020/10/26
 */
@Slf4j
public class RedisLock {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加锁
     * @author: lmf
     * @time: 2020/10/26 13:46
     * key 键
     * value: 当前时间+超时时间
     * 是否拿到锁
     */
    public boolean lock(String key,String value){
        if(redisTemplate.opsForValue().setIfAbsent(key,value)){
            return true;
        }
        String currentValue= (String) redisTemplate.opsForValue().get(key);
        //如果锁过期
        if(!StringUtils.isEmpty(currentValue)&&Long.parseLong(currentValue)<System.currentTimeMillis()){
            String oldValue= (String) redisTemplate.opsForValue().getAndSet(key,value);
            //是否已被别人抢占
            return StringUtils.isNotEmpty(oldValue)&&oldValue.equals(currentValue);
        }
        return false;
    }

    /**
     * 解锁
     * value:当前时间+超时时间
     */
    public void unLock(String key,String value){
      try{
          String currentValue= (String) redisTemplate.opsForValue().get(key);
          if(!StringUtils.isEmpty(currentValue)&&currentValue.equals(value)){
              redisTemplate.opsForValue().getOperations().delete(key);
          }
      }catch (Exception e){
          log.info("redis解锁异常");
      }
    }

}
